Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [1]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('/data/dog_images/train')
valid_files, valid_targets = load_dataset('/data/dog_images/valid')
test_files, test_targets = load_dataset('/data/dog_images/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("/data/dog_images/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
Using TensorFlow backend.
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [2]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("/data/lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [3]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [4]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer: From the result below we can see 100% of the first 100 images in human_files have a detected human face.

And it is 11% in dog_files.

In [5]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
human_image_detection = 0
for human_file in human_files_short:
    if(face_detector(human_file)):
        human_image_detection += 1

dog_image_detection = 0
for dog_file in dog_files_short:
    if(face_detector(dog_file)):
        dog_image_detection += 1

print("Human image detection percentage is {}%".format(human_image_detection))
print("Dog image detection percentage is {}%".format(dog_image_detection))
Human image detection percentage is 100%
Dog image detection percentage is 11%

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer:

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

I use a slight CNN similar to the algorithm below to detect images. The difference is the target. It is binary. First I combine 5000 human images and 5000 dog images as train_files. 1000 images are valid files and 1000 images are test files. Both half of them are human images and another half are dog images. In target files, '1' means human image and '0' means dog image.

GaussianNoise is used to add noise to train my algorithm to simulate the real condition. BatchNormalization[1] improves the accuracy. First I use the common method to train the model. Then I want to have a try the residual network as in [2] to train the model just for exploration. It is another story. We experience it in only 10 epochs.

[1] Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift, Sergey Ioffe, Christian Szegedy, https://arxiv.org/abs/1502.03167v3 [cs.CV]
[2] Identity Mappings in Deep Residual Networks, Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun, https://arxiv.org/abs/1603.05027v3 [cs.CV]

In [6]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.

human_train_files = human_files[:5000]
human_valid_files = human_files[5000:5500]
human_test_files = human_files[5500:6000]

dog_train_files = train_files[:5000]
dog_valid_files = valid_files[:500]
dog_test_files = test_files[:500]

total_train_files = np.concatenate((human_train_files, dog_train_files))
total_valid_files = np.concatenate((human_valid_files, dog_valid_files))
total_test_files = np.concatenate((human_test_files, dog_test_files))

total_train_targets = np.zeros((10000), dtype=int)
for i in range(0, 5000):
    total_train_targets[i] = 1
total_train_targets = np_utils.to_categorical(total_train_targets, 2)

total_valid_targets = np.zeros((1000), dtype=int)
for i in range(0, 500):
    total_valid_targets[i] = 1
total_valid_targets = np_utils.to_categorical(total_valid_targets, 2)
    
total_test_targets = np.zeros((1000), dtype=int)
for i in range(0, 500):
    total_test_targets[i] = 1
total_test_targets = np_utils.to_categorical(total_test_targets, 2)

Let's check the targets to make sure the labels are right.

In [7]:
print(total_train_targets[0])
print(total_train_targets[4999])
print(total_train_targets[5000])
print(total_train_targets[5001])
print()
print(total_valid_targets[0])
print(total_valid_targets[499])
print(total_valid_targets[500])
print(total_valid_targets[501])
print()
print(total_test_targets[0])
print(total_test_targets[499])
print(total_test_targets[500])
print(total_test_targets[501])
[ 0.  1.]
[ 0.  1.]
[ 1.  0.]
[ 1.  0.]

[ 0.  1.]
[ 0.  1.]
[ 1.  0.]
[ 1.  0.]

[ 0.  1.]
[ 0.  1.]
[ 1.  0.]
[ 1.  0.]
In [8]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)
In [9]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True     

# pre-process the data for Keras
def pre_process_image(img_path):
    return path_to_tensor(img_path).astype('float32')/255

def pre_process_images(img_paths):
    return paths_to_tensor(img_paths).astype('float32')/255
In [10]:
train_tensors = pre_process_images(total_train_files)
valid_tensors = pre_process_images(total_valid_files)
test_tensors = pre_process_images(total_test_files)
100%|██████████| 10000/10000 [01:15<00:00, 133.23it/s]
100%|██████████| 1000/1000 [00:09<00:00, 106.17it/s]
100%|██████████| 1000/1000 [00:07<00:00, 127.19it/s]
In [11]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense, Activation
from keras.layers.normalization import BatchNormalization
from keras.layers.noise import GaussianNoise
from keras.models import Sequential

model = Sequential()
# Block 1
model.add(Conv2D(filters=16, kernel_size=3, 
                 padding='same', input_shape=(224, 224, 3)))
model.add(MaxPooling2D(pool_size=2))
model.add(GaussianNoise(0.2))

# Block 2
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(filters=16, kernel_size=3, padding='same'))

model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(filters=16, kernel_size=3, padding='same'))

model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(filters=16, kernel_size=3, padding='same'))
model.add(MaxPooling2D(pool_size=2))

# Block 3
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(filters=32, kernel_size=3, padding='same'))

model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(filters=32, kernel_size=3, padding='same'))

model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(filters=32, kernel_size=3, padding='same'))
model.add(MaxPooling2D(pool_size=2))

# Block 4
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(filters=64, kernel_size=3, padding='same'))

model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(filters=64, kernel_size=3, padding='same'))

model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(filters=64, kernel_size=3, padding='same'))
model.add(MaxPooling2D(pool_size=2))

# Block 5
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(filters=128, kernel_size=3, padding='same'))

model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(filters=128, kernel_size=3, padding='same'))

model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(filters=128, kernel_size=3, padding='same'))
model.add(MaxPooling2D(pool_size=2))

model.add(GlobalAveragePooling2D())
model.add(Dense(2, activation='softmax'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 224, 224, 16)      448       
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 112, 112, 16)      0         
_________________________________________________________________
gaussian_noise_1 (GaussianNo (None, 112, 112, 16)      0         
_________________________________________________________________
batch_normalization_1 (Batch (None, 112, 112, 16)      64        
_________________________________________________________________
activation_1 (Activation)    (None, 112, 112, 16)      0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 112, 112, 16)      2320      
_________________________________________________________________
batch_normalization_2 (Batch (None, 112, 112, 16)      64        
_________________________________________________________________
activation_2 (Activation)    (None, 112, 112, 16)      0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 112, 112, 16)      2320      
_________________________________________________________________
batch_normalization_3 (Batch (None, 112, 112, 16)      64        
_________________________________________________________________
activation_3 (Activation)    (None, 112, 112, 16)      0         
_________________________________________________________________
conv2d_4 (Conv2D)            (None, 112, 112, 16)      2320      
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 56, 56, 16)        0         
_________________________________________________________________
batch_normalization_4 (Batch (None, 56, 56, 16)        64        
_________________________________________________________________
activation_4 (Activation)    (None, 56, 56, 16)        0         
_________________________________________________________________
conv2d_5 (Conv2D)            (None, 56, 56, 32)        4640      
_________________________________________________________________
batch_normalization_5 (Batch (None, 56, 56, 32)        128       
_________________________________________________________________
activation_5 (Activation)    (None, 56, 56, 32)        0         
_________________________________________________________________
conv2d_6 (Conv2D)            (None, 56, 56, 32)        9248      
_________________________________________________________________
batch_normalization_6 (Batch (None, 56, 56, 32)        128       
_________________________________________________________________
activation_6 (Activation)    (None, 56, 56, 32)        0         
_________________________________________________________________
conv2d_7 (Conv2D)            (None, 56, 56, 32)        9248      
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 28, 28, 32)        0         
_________________________________________________________________
batch_normalization_7 (Batch (None, 28, 28, 32)        128       
_________________________________________________________________
activation_7 (Activation)    (None, 28, 28, 32)        0         
_________________________________________________________________
conv2d_8 (Conv2D)            (None, 28, 28, 64)        18496     
_________________________________________________________________
batch_normalization_8 (Batch (None, 28, 28, 64)        256       
_________________________________________________________________
activation_8 (Activation)    (None, 28, 28, 64)        0         
_________________________________________________________________
conv2d_9 (Conv2D)            (None, 28, 28, 64)        36928     
_________________________________________________________________
batch_normalization_9 (Batch (None, 28, 28, 64)        256       
_________________________________________________________________
activation_9 (Activation)    (None, 28, 28, 64)        0         
_________________________________________________________________
conv2d_10 (Conv2D)           (None, 28, 28, 64)        36928     
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 14, 14, 64)        0         
_________________________________________________________________
batch_normalization_10 (Batc (None, 14, 14, 64)        256       
_________________________________________________________________
activation_10 (Activation)   (None, 14, 14, 64)        0         
_________________________________________________________________
conv2d_11 (Conv2D)           (None, 14, 14, 128)       73856     
_________________________________________________________________
batch_normalization_11 (Batc (None, 14, 14, 128)       512       
_________________________________________________________________
activation_11 (Activation)   (None, 14, 14, 128)       0         
_________________________________________________________________
conv2d_12 (Conv2D)           (None, 14, 14, 128)       147584    
_________________________________________________________________
batch_normalization_12 (Batc (None, 14, 14, 128)       512       
_________________________________________________________________
activation_12 (Activation)   (None, 14, 14, 128)       0         
_________________________________________________________________
conv2d_13 (Conv2D)           (None, 14, 14, 128)       147584    
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 7, 7, 128)         0         
_________________________________________________________________
global_average_pooling2d_1 ( (None, 128)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 2)                 258       
=================================================================
Total params: 494,610
Trainable params: 493,394
Non-trainable params: 1,216
_________________________________________________________________
In [12]:
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
In [13]:
from keras.callbacks import ModelCheckpoint

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)
model.fit(train_tensors, total_train_targets,
         validation_data=(valid_tensors, total_valid_targets),
         epochs=10, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 10000 samples, validate on 1000 samples
Epoch 1/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.4750 - acc: 0.8138Epoch 00001: val_loss improved from inf to 8.00030, saving model to saved_models/weights.best.from_scratch.hdf5
10000/10000 [==============================] - 82s 8ms/step - loss: 0.4744 - acc: 0.8141 - val_loss: 8.0003 - val_acc: 0.5000
Epoch 2/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.1527 - acc: 0.9438Epoch 00002: val_loss improved from 8.00030 to 6.16724, saving model to saved_models/weights.best.from_scratch.hdf5
10000/10000 [==============================] - 76s 8ms/step - loss: 0.1526 - acc: 0.9439 - val_loss: 6.1672 - val_acc: 0.5130
Epoch 3/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.0894 - acc: 0.9701Epoch 00003: val_loss did not improve
10000/10000 [==============================] - 76s 8ms/step - loss: 0.0894 - acc: 0.9701 - val_loss: 6.4710 - val_acc: 0.5120
Epoch 4/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.0527 - acc: 0.9819Epoch 00004: val_loss improved from 6.16724 to 2.02405, saving model to saved_models/weights.best.from_scratch.hdf5
10000/10000 [==============================] - 76s 8ms/step - loss: 0.0526 - acc: 0.9819 - val_loss: 2.0240 - val_acc: 0.6860
Epoch 5/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.0375 - acc: 0.9875Epoch 00005: val_loss did not improve
10000/10000 [==============================] - 76s 8ms/step - loss: 0.0375 - acc: 0.9875 - val_loss: 2.3881 - val_acc: 0.6460
Epoch 6/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.0291 - acc: 0.9909Epoch 00006: val_loss improved from 2.02405 to 0.16698, saving model to saved_models/weights.best.from_scratch.hdf5
10000/10000 [==============================] - 76s 8ms/step - loss: 0.0295 - acc: 0.9908 - val_loss: 0.1670 - val_acc: 0.9500
Epoch 7/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.0256 - acc: 0.9916Epoch 00007: val_loss did not improve
10000/10000 [==============================] - 76s 8ms/step - loss: 0.0255 - acc: 0.9916 - val_loss: 1.4746 - val_acc: 0.7720
Epoch 8/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.0157 - acc: 0.9945Epoch 00008: val_loss did not improve
10000/10000 [==============================] - 76s 8ms/step - loss: 0.0157 - acc: 0.9945 - val_loss: 2.7817 - val_acc: 0.6430
Epoch 9/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.0157 - acc: 0.9947Epoch 00009: val_loss improved from 0.16698 to 0.08667, saving model to saved_models/weights.best.from_scratch.hdf5
10000/10000 [==============================] - 76s 8ms/step - loss: 0.0157 - acc: 0.9947 - val_loss: 0.0867 - val_acc: 0.9730
Epoch 10/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.0132 - acc: 0.9966Epoch 00010: val_loss did not improve
10000/10000 [==============================] - 76s 8ms/step - loss: 0.0132 - acc: 0.9966 - val_loss: 0.2029 - val_acc: 0.9390
Out[13]:
<keras.callbacks.History at 0x7f2a55d679e8>
In [14]:
# get index of predicted for each image in test set
predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100.0*np.sum(np.array(predictions)[:1000]==np.argmax(total_test_targets, axis=1)[:1000])/len(predictions)
print('Test accuracy: %.1f%%' % test_accuracy)
Test accuracy: 93.7%

Let's have a look at the resnet result.

In [17]:
from keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, ZeroPadding2D
from keras.layers import Dense, Flatten, Activation, Input, add
from keras.layers.normalization import BatchNormalization
from keras.layers.noise import GaussianNoise
from keras.models import Model

def Conv2d_BN(x, nb_filter, kernel_size, strides=(1,1), 
              padding='same', name=None):
    if name is not None:
        bn_name = name + '_bn'
        conv_name = name + '_conv'
    else:
        bn_name = None
        conv_name = None
    
    x = Conv2D(nb_filter, kernel_size, padding=padding, 
               strides=strides, name=conv_name)(x)
    x = BatchNormalization(axis=3, name=bn_name)(x)
    x = Activation('relu')(x)
    return x
 

def identity_Block(inpt, nb_filter, kernel_size, strides=(1,1), 
                   with_conv_shortcut=False):
    
    x = Conv2d_BN(inpt, nb_filter=nb_filter, kernel_size=kernel_size, strides=strides, padding='same')
    x = Conv2d_BN(x, nb_filter=nb_filter, kernel_size=kernel_size, padding='same')

    if with_conv_shortcut:
        shortcut = Conv2d_BN(inpt, nb_filter=nb_filter, kernel_size=kernel_size, strides=strides)
        x = add([x, shortcut])
        return x
    else:
        x = add([x, inpt])
        return x
    
    
def resnet(width, height, channel, classes):
    inpt = Input(shape=(width, height, channel))
    
    #conv1
    x = Conv2d_BN(inpt, nb_filter=16, kernel_size=(3, 3), strides=(2, 2), padding='valid')
    x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)
    x = GaussianNoise(0.2)(x)
    
    #conv2_x
    x = identity_Block(x, nb_filter=16, kernel_size=(3, 3))
    x = identity_Block(x, nb_filter=16, kernel_size=(3, 3))   
    x = identity_Block(x, nb_filter=16, kernel_size=(3, 3))   

    #conv3_x
    x = identity_Block(x, nb_filter=32, kernel_size=(3, 3), strides=(2, 2), with_conv_shortcut=True)
    x = identity_Block(x, nb_filter=32, kernel_size=(3, 3))
    x = identity_Block(x, nb_filter=32, kernel_size=(3, 3))

    #conv4_x
    x = identity_Block(x, nb_filter=64, kernel_size=(3, 3), strides=(2, 2), with_conv_shortcut=True)
    x = identity_Block(x, nb_filter=64, kernel_size=(3, 3))
    x = identity_Block(x, nb_filter=64, kernel_size=(3, 3))
    
    #conv5_x
    x = identity_Block(x, nb_filter=128, kernel_size=(3, 3), strides=(2, 2), with_conv_shortcut=True)    
    x = identity_Block(x, nb_filter=128, kernel_size=(3, 3))
    x = identity_Block(x, nb_filter=128, kernel_size=(3, 3))
    
    x = AveragePooling2D(pool_size=(7, 7))(x)
    x = Flatten()(x)
    x = Dense(classes, activation='softmax')(x)
    
    model = Model(inputs=inpt, outputs=x)
    return model
 

model = resnet(224, 224, 3, 2)  
model.summary()
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to                     
==================================================================================================
input_4 (InputLayer)            (None, 224, 224, 3)  0                                            
__________________________________________________________________________________________________
conv2d_57 (Conv2D)              (None, 111, 111, 16) 448         input_4[0][0]                    
__________________________________________________________________________________________________
batch_normalization_57 (BatchNo (None, 111, 111, 16) 64          conv2d_57[0][0]                  
__________________________________________________________________________________________________
activation_57 (Activation)      (None, 111, 111, 16) 0           batch_normalization_57[0][0]     
__________________________________________________________________________________________________
max_pooling2d_3 (MaxPooling2D)  (None, 56, 56, 16)   0           activation_57[0][0]              
__________________________________________________________________________________________________
gaussian_noise_3 (GaussianNoise (None, 56, 56, 16)   0           max_pooling2d_3[0][0]            
__________________________________________________________________________________________________
conv2d_58 (Conv2D)              (None, 56, 56, 16)   2320        gaussian_noise_3[0][0]           
__________________________________________________________________________________________________
batch_normalization_58 (BatchNo (None, 56, 56, 16)   64          conv2d_58[0][0]                  
__________________________________________________________________________________________________
activation_58 (Activation)      (None, 56, 56, 16)   0           batch_normalization_58[0][0]     
__________________________________________________________________________________________________
conv2d_59 (Conv2D)              (None, 56, 56, 16)   2320        activation_58[0][0]              
__________________________________________________________________________________________________
batch_normalization_59 (BatchNo (None, 56, 56, 16)   64          conv2d_59[0][0]                  
__________________________________________________________________________________________________
activation_59 (Activation)      (None, 56, 56, 16)   0           batch_normalization_59[0][0]     
__________________________________________________________________________________________________
add_25 (Add)                    (None, 56, 56, 16)   0           activation_59[0][0]              
                                                                 gaussian_noise_3[0][0]           
__________________________________________________________________________________________________
conv2d_60 (Conv2D)              (None, 56, 56, 16)   2320        add_25[0][0]                     
__________________________________________________________________________________________________
batch_normalization_60 (BatchNo (None, 56, 56, 16)   64          conv2d_60[0][0]                  
__________________________________________________________________________________________________
activation_60 (Activation)      (None, 56, 56, 16)   0           batch_normalization_60[0][0]     
__________________________________________________________________________________________________
conv2d_61 (Conv2D)              (None, 56, 56, 16)   2320        activation_60[0][0]              
__________________________________________________________________________________________________
batch_normalization_61 (BatchNo (None, 56, 56, 16)   64          conv2d_61[0][0]                  
__________________________________________________________________________________________________
activation_61 (Activation)      (None, 56, 56, 16)   0           batch_normalization_61[0][0]     
__________________________________________________________________________________________________
add_26 (Add)                    (None, 56, 56, 16)   0           activation_61[0][0]              
                                                                 add_25[0][0]                     
__________________________________________________________________________________________________
conv2d_62 (Conv2D)              (None, 56, 56, 16)   2320        add_26[0][0]                     
__________________________________________________________________________________________________
batch_normalization_62 (BatchNo (None, 56, 56, 16)   64          conv2d_62[0][0]                  
__________________________________________________________________________________________________
activation_62 (Activation)      (None, 56, 56, 16)   0           batch_normalization_62[0][0]     
__________________________________________________________________________________________________
conv2d_63 (Conv2D)              (None, 56, 56, 16)   2320        activation_62[0][0]              
__________________________________________________________________________________________________
batch_normalization_63 (BatchNo (None, 56, 56, 16)   64          conv2d_63[0][0]                  
__________________________________________________________________________________________________
activation_63 (Activation)      (None, 56, 56, 16)   0           batch_normalization_63[0][0]     
__________________________________________________________________________________________________
add_27 (Add)                    (None, 56, 56, 16)   0           activation_63[0][0]              
                                                                 add_26[0][0]                     
__________________________________________________________________________________________________
conv2d_64 (Conv2D)              (None, 28, 28, 32)   4640        add_27[0][0]                     
__________________________________________________________________________________________________
batch_normalization_64 (BatchNo (None, 28, 28, 32)   128         conv2d_64[0][0]                  
__________________________________________________________________________________________________
activation_64 (Activation)      (None, 28, 28, 32)   0           batch_normalization_64[0][0]     
__________________________________________________________________________________________________
conv2d_65 (Conv2D)              (None, 28, 28, 32)   9248        activation_64[0][0]              
__________________________________________________________________________________________________
conv2d_66 (Conv2D)              (None, 28, 28, 32)   4640        add_27[0][0]                     
__________________________________________________________________________________________________
batch_normalization_65 (BatchNo (None, 28, 28, 32)   128         conv2d_65[0][0]                  
__________________________________________________________________________________________________
batch_normalization_66 (BatchNo (None, 28, 28, 32)   128         conv2d_66[0][0]                  
__________________________________________________________________________________________________
activation_65 (Activation)      (None, 28, 28, 32)   0           batch_normalization_65[0][0]     
__________________________________________________________________________________________________
activation_66 (Activation)      (None, 28, 28, 32)   0           batch_normalization_66[0][0]     
__________________________________________________________________________________________________
add_28 (Add)                    (None, 28, 28, 32)   0           activation_65[0][0]              
                                                                 activation_66[0][0]              
__________________________________________________________________________________________________
conv2d_67 (Conv2D)              (None, 28, 28, 32)   9248        add_28[0][0]                     
__________________________________________________________________________________________________
batch_normalization_67 (BatchNo (None, 28, 28, 32)   128         conv2d_67[0][0]                  
__________________________________________________________________________________________________
activation_67 (Activation)      (None, 28, 28, 32)   0           batch_normalization_67[0][0]     
__________________________________________________________________________________________________
conv2d_68 (Conv2D)              (None, 28, 28, 32)   9248        activation_67[0][0]              
__________________________________________________________________________________________________
batch_normalization_68 (BatchNo (None, 28, 28, 32)   128         conv2d_68[0][0]                  
__________________________________________________________________________________________________
activation_68 (Activation)      (None, 28, 28, 32)   0           batch_normalization_68[0][0]     
__________________________________________________________________________________________________
add_29 (Add)                    (None, 28, 28, 32)   0           activation_68[0][0]              
                                                                 add_28[0][0]                     
__________________________________________________________________________________________________
conv2d_69 (Conv2D)              (None, 28, 28, 32)   9248        add_29[0][0]                     
__________________________________________________________________________________________________
batch_normalization_69 (BatchNo (None, 28, 28, 32)   128         conv2d_69[0][0]                  
__________________________________________________________________________________________________
activation_69 (Activation)      (None, 28, 28, 32)   0           batch_normalization_69[0][0]     
__________________________________________________________________________________________________
conv2d_70 (Conv2D)              (None, 28, 28, 32)   9248        activation_69[0][0]              
__________________________________________________________________________________________________
batch_normalization_70 (BatchNo (None, 28, 28, 32)   128         conv2d_70[0][0]                  
__________________________________________________________________________________________________
activation_70 (Activation)      (None, 28, 28, 32)   0           batch_normalization_70[0][0]     
__________________________________________________________________________________________________
add_30 (Add)                    (None, 28, 28, 32)   0           activation_70[0][0]              
                                                                 add_29[0][0]                     
__________________________________________________________________________________________________
conv2d_71 (Conv2D)              (None, 14, 14, 64)   18496       add_30[0][0]                     
__________________________________________________________________________________________________
batch_normalization_71 (BatchNo (None, 14, 14, 64)   256         conv2d_71[0][0]                  
__________________________________________________________________________________________________
activation_71 (Activation)      (None, 14, 14, 64)   0           batch_normalization_71[0][0]     
__________________________________________________________________________________________________
conv2d_72 (Conv2D)              (None, 14, 14, 64)   36928       activation_71[0][0]              
__________________________________________________________________________________________________
conv2d_73 (Conv2D)              (None, 14, 14, 64)   18496       add_30[0][0]                     
__________________________________________________________________________________________________
batch_normalization_72 (BatchNo (None, 14, 14, 64)   256         conv2d_72[0][0]                  
__________________________________________________________________________________________________
batch_normalization_73 (BatchNo (None, 14, 14, 64)   256         conv2d_73[0][0]                  
__________________________________________________________________________________________________
activation_72 (Activation)      (None, 14, 14, 64)   0           batch_normalization_72[0][0]     
__________________________________________________________________________________________________
activation_73 (Activation)      (None, 14, 14, 64)   0           batch_normalization_73[0][0]     
__________________________________________________________________________________________________
add_31 (Add)                    (None, 14, 14, 64)   0           activation_72[0][0]              
                                                                 activation_73[0][0]              
__________________________________________________________________________________________________
conv2d_74 (Conv2D)              (None, 14, 14, 64)   36928       add_31[0][0]                     
__________________________________________________________________________________________________
batch_normalization_74 (BatchNo (None, 14, 14, 64)   256         conv2d_74[0][0]                  
__________________________________________________________________________________________________
activation_74 (Activation)      (None, 14, 14, 64)   0           batch_normalization_74[0][0]     
__________________________________________________________________________________________________
conv2d_75 (Conv2D)              (None, 14, 14, 64)   36928       activation_74[0][0]              
__________________________________________________________________________________________________
batch_normalization_75 (BatchNo (None, 14, 14, 64)   256         conv2d_75[0][0]                  
__________________________________________________________________________________________________
activation_75 (Activation)      (None, 14, 14, 64)   0           batch_normalization_75[0][0]     
__________________________________________________________________________________________________
add_32 (Add)                    (None, 14, 14, 64)   0           activation_75[0][0]              
                                                                 add_31[0][0]                     
__________________________________________________________________________________________________
conv2d_76 (Conv2D)              (None, 14, 14, 64)   36928       add_32[0][0]                     
__________________________________________________________________________________________________
batch_normalization_76 (BatchNo (None, 14, 14, 64)   256         conv2d_76[0][0]                  
__________________________________________________________________________________________________
activation_76 (Activation)      (None, 14, 14, 64)   0           batch_normalization_76[0][0]     
__________________________________________________________________________________________________
conv2d_77 (Conv2D)              (None, 14, 14, 64)   36928       activation_76[0][0]              
__________________________________________________________________________________________________
batch_normalization_77 (BatchNo (None, 14, 14, 64)   256         conv2d_77[0][0]                  
__________________________________________________________________________________________________
activation_77 (Activation)      (None, 14, 14, 64)   0           batch_normalization_77[0][0]     
__________________________________________________________________________________________________
add_33 (Add)                    (None, 14, 14, 64)   0           activation_77[0][0]              
                                                                 add_32[0][0]                     
__________________________________________________________________________________________________
conv2d_78 (Conv2D)              (None, 7, 7, 128)    73856       add_33[0][0]                     
__________________________________________________________________________________________________
batch_normalization_78 (BatchNo (None, 7, 7, 128)    512         conv2d_78[0][0]                  
__________________________________________________________________________________________________
activation_78 (Activation)      (None, 7, 7, 128)    0           batch_normalization_78[0][0]     
__________________________________________________________________________________________________
conv2d_79 (Conv2D)              (None, 7, 7, 128)    147584      activation_78[0][0]              
__________________________________________________________________________________________________
conv2d_80 (Conv2D)              (None, 7, 7, 128)    73856       add_33[0][0]                     
__________________________________________________________________________________________________
batch_normalization_79 (BatchNo (None, 7, 7, 128)    512         conv2d_79[0][0]                  
__________________________________________________________________________________________________
batch_normalization_80 (BatchNo (None, 7, 7, 128)    512         conv2d_80[0][0]                  
__________________________________________________________________________________________________
activation_79 (Activation)      (None, 7, 7, 128)    0           batch_normalization_79[0][0]     
__________________________________________________________________________________________________
activation_80 (Activation)      (None, 7, 7, 128)    0           batch_normalization_80[0][0]     
__________________________________________________________________________________________________
add_34 (Add)                    (None, 7, 7, 128)    0           activation_79[0][0]              
                                                                 activation_80[0][0]              
__________________________________________________________________________________________________
conv2d_81 (Conv2D)              (None, 7, 7, 128)    147584      add_34[0][0]                     
__________________________________________________________________________________________________
batch_normalization_81 (BatchNo (None, 7, 7, 128)    512         conv2d_81[0][0]                  
__________________________________________________________________________________________________
activation_81 (Activation)      (None, 7, 7, 128)    0           batch_normalization_81[0][0]     
__________________________________________________________________________________________________
conv2d_82 (Conv2D)              (None, 7, 7, 128)    147584      activation_81[0][0]              
__________________________________________________________________________________________________
batch_normalization_82 (BatchNo (None, 7, 7, 128)    512         conv2d_82[0][0]                  
__________________________________________________________________________________________________
activation_82 (Activation)      (None, 7, 7, 128)    0           batch_normalization_82[0][0]     
__________________________________________________________________________________________________
add_35 (Add)                    (None, 7, 7, 128)    0           activation_82[0][0]              
                                                                 add_34[0][0]                     
__________________________________________________________________________________________________
conv2d_83 (Conv2D)              (None, 7, 7, 128)    147584      add_35[0][0]                     
__________________________________________________________________________________________________
batch_normalization_83 (BatchNo (None, 7, 7, 128)    512         conv2d_83[0][0]                  
__________________________________________________________________________________________________
activation_83 (Activation)      (None, 7, 7, 128)    0           batch_normalization_83[0][0]     
__________________________________________________________________________________________________
conv2d_84 (Conv2D)              (None, 7, 7, 128)    147584      activation_83[0][0]              
__________________________________________________________________________________________________
batch_normalization_84 (BatchNo (None, 7, 7, 128)    512         conv2d_84[0][0]                  
__________________________________________________________________________________________________
activation_84 (Activation)      (None, 7, 7, 128)    0           batch_normalization_84[0][0]     
__________________________________________________________________________________________________
add_36 (Add)                    (None, 7, 7, 128)    0           activation_84[0][0]              
                                                                 add_35[0][0]                     
__________________________________________________________________________________________________
average_pooling2d_3 (AveragePoo (None, 1, 1, 128)    0           add_36[0][0]                     
__________________________________________________________________________________________________
flatten_3 (Flatten)             (None, 128)          0           average_pooling2d_3[0][0]        
__________________________________________________________________________________________________
dense_2 (Dense)                 (None, 2)            258         flatten_3[0][0]                  
==================================================================================================
Total params: 1,184,130
Trainable params: 1,180,770
Non-trainable params: 3,360
__________________________________________________________________________________________________
In [18]:
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
In [19]:
from keras.callbacks import ModelCheckpoint

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)
model.fit(train_tensors, total_train_targets,
         validation_data=(valid_tensors, total_valid_targets),
         epochs=10, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 10000 samples, validate on 1000 samples
Epoch 1/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.1432 - acc: 0.9501Epoch 00001: val_loss improved from inf to 0.06262, saving model to saved_models/weights.best.from_scratch.hdf5
10000/10000 [==============================] - 67s 7ms/step - loss: 0.1429 - acc: 0.9502 - val_loss: 0.0626 - val_acc: 0.9800
Epoch 2/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.0275 - acc: 0.9912Epoch 00002: val_loss did not improve
10000/10000 [==============================] - 60s 6ms/step - loss: 0.0274 - acc: 0.9912 - val_loss: 0.0659 - val_acc: 0.9730
Epoch 3/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.0152 - acc: 0.9947Epoch 00003: val_loss did not improve
10000/10000 [==============================] - 60s 6ms/step - loss: 0.0152 - acc: 0.9947 - val_loss: 0.0830 - val_acc: 0.9810
Epoch 4/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.0126 - acc: 0.9965Epoch 00004: val_loss did not improve
10000/10000 [==============================] - 60s 6ms/step - loss: 0.0125 - acc: 0.9965 - val_loss: 0.6657 - val_acc: 0.8280
Epoch 5/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.0083 - acc: 0.9975Epoch 00005: val_loss improved from 0.06262 to 0.00802, saving model to saved_models/weights.best.from_scratch.hdf5
10000/10000 [==============================] - 60s 6ms/step - loss: 0.0082 - acc: 0.9975 - val_loss: 0.0080 - val_acc: 0.9970
Epoch 6/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.0094 - acc: 0.9977Epoch 00006: val_loss did not improve
10000/10000 [==============================] - 60s 6ms/step - loss: 0.0094 - acc: 0.9977 - val_loss: 0.0203 - val_acc: 0.9940
Epoch 7/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.0039 - acc: 0.9987Epoch 00007: val_loss did not improve
10000/10000 [==============================] - 60s 6ms/step - loss: 0.0039 - acc: 0.9987 - val_loss: 0.0912 - val_acc: 0.9760
Epoch 8/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.0050 - acc: 0.9983Epoch 00008: val_loss improved from 0.00802 to 0.00759, saving model to saved_models/weights.best.from_scratch.hdf5
10000/10000 [==============================] - 60s 6ms/step - loss: 0.0050 - acc: 0.9983 - val_loss: 0.0076 - val_acc: 0.9970
Epoch 9/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.0047 - acc: 0.9988Epoch 00009: val_loss did not improve
10000/10000 [==============================] - 60s 6ms/step - loss: 0.0047 - acc: 0.9988 - val_loss: 0.0875 - val_acc: 0.9800
Epoch 10/10
 9980/10000 [============================>.] - ETA: 0s - loss: 0.0043 - acc: 0.9989Epoch 00010: val_loss improved from 0.00759 to 0.00464, saving model to saved_models/weights.best.from_scratch.hdf5
10000/10000 [==============================] - 60s 6ms/step - loss: 0.0043 - acc: 0.9989 - val_loss: 0.0046 - val_acc: 0.9990
Out[19]:
<keras.callbacks.History at 0x7f99e88c6cc0>
In [20]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')
In [21]:
# get index of predicted for each image in test set
predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100.0*np.sum(np.array(predictions)[:1000]==np.argmax(total_test_targets, axis=1)[:1000])/len(predictions)
print('Test accuracy: %.1f%%' % test_accuracy)
Test accuracy: 100.0%

We can see that resnet takes less time for every epoch and gets a higher test accuracy. It is unbelievable 100%. Let's check the results in this algorithm for human images and dog images and it should ouput '1' and '0' repectively.

In [22]:
predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) 
               for tensor in pre_process_images(human_files[8000:8020])]
print(predictions)                                                                                                        
100%|██████████| 20/20 [00:00<00:00, 142.98it/s]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
In [23]:
predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) 
               for tensor in pre_process_images(test_files[800:820])]
print(predictions)       
100%|██████████| 20/20 [00:00<00:00, 91.28it/s]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

It is OK for this algorithm.


Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [24]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')
Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels.h5
102858752/102853048 [==============================] - 5s 0us/step

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [30]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [26]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [27]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer: We can see that 0% of the images in human_files_short have a detected dog and it is 100% in dog_files_short.

In [28]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

human_image_detection = 0
for human_file in human_files_short:
    if(dog_detector(human_file)):
        human_image_detection += 1

dog_image_detection = 0
for dog_file in dog_files_short:
    if(dog_detector(dog_file)):
        dog_image_detection += 1

print("{}% of the images in human_files_short have a detected dog.".format(human_image_detection))
print("{}% of the images in dog_files_short have a detected dog.".format(dog_image_detection))
0% of the images in human_files_short have a detected dog.
100% of the images in dog_files_short have a detected dog.

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [29]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [01:26<00:00, 49.97it/s] 
100%|██████████| 835/835 [00:13<00:00, 61.11it/s]
100%|██████████| 836/836 [00:09<00:00, 83.79it/s] 

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer: I add some layers to improve the accuracy and it's not too deep in order not to take much time and overfit. Batch Normalization is to reduce the internal covariate shift as in the paper[1] above. MaxPooling is to reduce the dimensionality. Small kernel_size can imporve accuracy as well as a little deep layer.

In [31]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Activation, Dense
from keras.layers.normalization import BatchNormalization
from keras.models import Sequential

### TODO: Define your architecture.
model = Sequential()
model.add(Conv2D(filters=32, kernel_size=3, padding='same', 
                activation='relu', input_shape=(224, 224, 3)))
model.add(MaxPooling2D(pool_size=2))

model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(filters=32, kernel_size=3, padding='same'))

model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(filters=32, kernel_size=3, padding='same'))
model.add(MaxPooling2D(pool_size=2))

model.add(BatchNormalization())
model.add(Activation('relu'))    
model.add(Conv2D(filters=64, kernel_size=3, padding='same'))

model.add(BatchNormalization())
model.add(Activation('relu')) 
model.add(Conv2D(filters=64, kernel_size=3, padding='same'))
model.add(MaxPooling2D(pool_size=2))

model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(filters=128, kernel_size=3, padding='same'))

model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Conv2D(filters=128, kernel_size=3, padding='same'))
model.add(MaxPooling2D(pool_size=2))

model.add(GlobalAveragePooling2D())
model.add(Dense(133, activation='softmax'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_85 (Conv2D)           (None, 224, 224, 32)      896       
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 112, 112, 32)      0         
_________________________________________________________________
batch_normalization_85 (Batc (None, 112, 112, 32)      128       
_________________________________________________________________
activation_134 (Activation)  (None, 112, 112, 32)      0         
_________________________________________________________________
conv2d_86 (Conv2D)           (None, 112, 112, 32)      9248      
_________________________________________________________________
batch_normalization_86 (Batc (None, 112, 112, 32)      128       
_________________________________________________________________
activation_135 (Activation)  (None, 112, 112, 32)      0         
_________________________________________________________________
conv2d_87 (Conv2D)           (None, 112, 112, 32)      9248      
_________________________________________________________________
max_pooling2d_6 (MaxPooling2 (None, 56, 56, 32)        0         
_________________________________________________________________
batch_normalization_87 (Batc (None, 56, 56, 32)        128       
_________________________________________________________________
activation_136 (Activation)  (None, 56, 56, 32)        0         
_________________________________________________________________
conv2d_88 (Conv2D)           (None, 56, 56, 64)        18496     
_________________________________________________________________
batch_normalization_88 (Batc (None, 56, 56, 64)        256       
_________________________________________________________________
activation_137 (Activation)  (None, 56, 56, 64)        0         
_________________________________________________________________
conv2d_89 (Conv2D)           (None, 56, 56, 64)        36928     
_________________________________________________________________
max_pooling2d_7 (MaxPooling2 (None, 28, 28, 64)        0         
_________________________________________________________________
batch_normalization_89 (Batc (None, 28, 28, 64)        256       
_________________________________________________________________
activation_138 (Activation)  (None, 28, 28, 64)        0         
_________________________________________________________________
conv2d_90 (Conv2D)           (None, 28, 28, 128)       73856     
_________________________________________________________________
batch_normalization_90 (Batc (None, 28, 28, 128)       512       
_________________________________________________________________
activation_139 (Activation)  (None, 28, 28, 128)       0         
_________________________________________________________________
conv2d_91 (Conv2D)           (None, 28, 28, 128)       147584    
_________________________________________________________________
max_pooling2d_8 (MaxPooling2 (None, 14, 14, 128)       0         
_________________________________________________________________
global_average_pooling2d_1 ( (None, 128)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 133)               17157     
=================================================================
Total params: 314,821
Trainable params: 314,117
Non-trainable params: 704
_________________________________________________________________

Compile the Model

In [32]:
import keras.optimizers as optimizer
model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [33]:
# create and configure augmented image generator
from keras.preprocessing.image import ImageDataGenerator

datagen_train = ImageDataGenerator(
    width_shift_range=0.1,     # randomly shift images horizontally (10% of total width)
    height_shift_range=0.1,    # randomly shift images vertically (10% of total height)
    horizontal_flip=True)      # randomly flip images horizontally

datagen_valid = ImageDataGenerator(
    width_shift_range=0.1,     # randomly shift images horizontally (10% of total width)
    height_shift_range=0.1,    # randomly shift images vertically (10% of total height)
    horizontal_flip=True)      # randomly flip images horizontally

# fit augment image generator on data
datagen_train.fit(train_tensors)
datagen_valid.fit(valid_tensors)
In [34]:
from keras.callbacks import ModelCheckpoint  

### TODO: specify the number of epochs that you would like to use to train the model.
epochs = 20

### Do NOT modify the code below this line.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.8608 - acc: 0.0158Epoch 00001: val_loss improved from inf to 4.91688, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 62s 9ms/step - loss: 4.8610 - acc: 0.0157 - val_loss: 4.9169 - val_acc: 0.0096
Epoch 2/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.7388 - acc: 0.0279Epoch 00002: val_loss improved from 4.91688 to 4.76440, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 56s 8ms/step - loss: 4.7387 - acc: 0.0280 - val_loss: 4.7644 - val_acc: 0.0240
Epoch 3/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.6456 - acc: 0.0377Epoch 00003: val_loss improved from 4.76440 to 4.71952, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 56s 8ms/step - loss: 4.6457 - acc: 0.0376 - val_loss: 4.7195 - val_acc: 0.0287
Epoch 4/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.5535 - acc: 0.0393Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 56s 8ms/step - loss: 4.5538 - acc: 0.0392 - val_loss: 4.8648 - val_acc: 0.0240
Epoch 5/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.4563 - acc: 0.0461Epoch 00005: val_loss improved from 4.71952 to 4.69738, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 56s 8ms/step - loss: 4.4564 - acc: 0.0461 - val_loss: 4.6974 - val_acc: 0.0371
Epoch 6/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.3572 - acc: 0.0544Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 56s 8ms/step - loss: 4.3573 - acc: 0.0543 - val_loss: 4.7065 - val_acc: 0.0383
Epoch 7/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.2724 - acc: 0.0653Epoch 00007: val_loss improved from 4.69738 to 4.66318, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 56s 8ms/step - loss: 4.2710 - acc: 0.0654 - val_loss: 4.6632 - val_acc: 0.0383
Epoch 8/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.1910 - acc: 0.0694Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 56s 8ms/step - loss: 4.1904 - acc: 0.0695 - val_loss: 4.6829 - val_acc: 0.0275
Epoch 9/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.1036 - acc: 0.0767Epoch 00009: val_loss improved from 4.66318 to 4.46748, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 56s 8ms/step - loss: 4.1029 - acc: 0.0771 - val_loss: 4.4675 - val_acc: 0.0503
Epoch 10/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.0250 - acc: 0.0898Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 56s 8ms/step - loss: 4.0236 - acc: 0.0901 - val_loss: 4.7543 - val_acc: 0.0371
Epoch 11/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.9526 - acc: 0.0973Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 56s 8ms/step - loss: 3.9526 - acc: 0.0973 - val_loss: 4.5927 - val_acc: 0.0443
Epoch 12/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.8784 - acc: 0.1081Epoch 00012: val_loss improved from 4.46748 to 4.19828, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 56s 8ms/step - loss: 3.8786 - acc: 0.1081 - val_loss: 4.1983 - val_acc: 0.0898
Epoch 13/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.8152 - acc: 0.1141Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 56s 8ms/step - loss: 3.8162 - acc: 0.1144 - val_loss: 4.4082 - val_acc: 0.0659
Epoch 14/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.7343 - acc: 0.1212Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 56s 8ms/step - loss: 3.7341 - acc: 0.1214 - val_loss: 4.4897 - val_acc: 0.0539
Epoch 15/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.6668 - acc: 0.1267Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 56s 8ms/step - loss: 3.6667 - acc: 0.1265 - val_loss: 6.7243 - val_acc: 0.0515
Epoch 16/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.6225 - acc: 0.1396Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 56s 8ms/step - loss: 3.6216 - acc: 0.1400 - val_loss: 4.2075 - val_acc: 0.1054
Epoch 17/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.5534 - acc: 0.1482Epoch 00017: val_loss improved from 4.19828 to 4.10566, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 56s 8ms/step - loss: 3.5525 - acc: 0.1484 - val_loss: 4.1057 - val_acc: 0.0826
Epoch 18/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.5060 - acc: 0.1565Epoch 00018: val_loss improved from 4.10566 to 3.80022, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 56s 8ms/step - loss: 3.5056 - acc: 0.1564 - val_loss: 3.8002 - val_acc: 0.1174
Epoch 19/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.4449 - acc: 0.1613Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 56s 8ms/step - loss: 3.4460 - acc: 0.1614 - val_loss: 4.3588 - val_acc: 0.0719
Epoch 20/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.3932 - acc: 0.1802Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 56s 8ms/step - loss: 3.3924 - acc: 0.1801 - val_loss: 4.3178 - val_acc: 0.0659
Out[34]:
<keras.callbacks.History at 0x7f9b5be748d0>

Load the Model with the Best Validation Loss

In [35]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [36]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 11.7225%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [37]:
bottleneck_features = np.load('/data/bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [38]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_2 ( (None, 512)               0         
_________________________________________________________________
dense_4 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [39]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [40]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6600/6680 [============================>.] - ETA: 0s - loss: 13.1397 - acc: 0.0941Epoch 00001: val_loss improved from inf to 11.59733, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 4s 642us/step - loss: 13.1173 - acc: 0.0952 - val_loss: 11.5973 - val_acc: 0.1784
Epoch 2/20
6520/6680 [============================>.] - ETA: 0s - loss: 11.2123 - acc: 0.2319Epoch 00002: val_loss improved from 11.59733 to 11.18483, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 268us/step - loss: 11.1948 - acc: 0.2326 - val_loss: 11.1848 - val_acc: 0.2275
Epoch 3/20
6540/6680 [============================>.] - ETA: 0s - loss: 10.7606 - acc: 0.2821Epoch 00003: val_loss improved from 11.18483 to 10.93323, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 266us/step - loss: 10.7585 - acc: 0.2817 - val_loss: 10.9332 - val_acc: 0.2515
Epoch 4/20
6500/6680 [============================>.] - ETA: 0s - loss: 10.5136 - acc: 0.3065Epoch 00004: val_loss improved from 10.93323 to 10.87681, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 265us/step - loss: 10.5128 - acc: 0.3070 - val_loss: 10.8768 - val_acc: 0.2623
Epoch 5/20
6460/6680 [============================>.] - ETA: 0s - loss: 10.3443 - acc: 0.3245Epoch 00005: val_loss improved from 10.87681 to 10.70823, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 275us/step - loss: 10.3357 - acc: 0.3257 - val_loss: 10.7082 - val_acc: 0.2743
Epoch 6/20
6620/6680 [============================>.] - ETA: 0s - loss: 10.1945 - acc: 0.3435Epoch 00006: val_loss improved from 10.70823 to 10.69269, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 261us/step - loss: 10.1957 - acc: 0.3434 - val_loss: 10.6927 - val_acc: 0.2778
Epoch 7/20
6500/6680 [============================>.] - ETA: 0s - loss: 10.1151 - acc: 0.3525Epoch 00007: val_loss improved from 10.69269 to 10.54835, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 271us/step - loss: 10.1447 - acc: 0.3499 - val_loss: 10.5483 - val_acc: 0.2910
Epoch 8/20
6560/6680 [============================>.] - ETA: 0s - loss: 10.0053 - acc: 0.3598Epoch 00008: val_loss improved from 10.54835 to 10.49782, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 267us/step - loss: 10.0045 - acc: 0.3600 - val_loss: 10.4978 - val_acc: 0.2874
Epoch 9/20
6560/6680 [============================>.] - ETA: 0s - loss: 9.8083 - acc: 0.3698Epoch 00009: val_loss improved from 10.49782 to 10.20129, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 267us/step - loss: 9.7921 - acc: 0.3710 - val_loss: 10.2013 - val_acc: 0.3114
Epoch 10/20
6520/6680 [============================>.] - ETA: 0s - loss: 9.6731 - acc: 0.3847Epoch 00010: val_loss improved from 10.20129 to 10.15539, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 268us/step - loss: 9.6928 - acc: 0.3837 - val_loss: 10.1554 - val_acc: 0.3078
Epoch 11/20
6540/6680 [============================>.] - ETA: 0s - loss: 9.6663 - acc: 0.3885Epoch 00011: val_loss improved from 10.15539 to 10.14360, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 268us/step - loss: 9.6393 - acc: 0.3900 - val_loss: 10.1436 - val_acc: 0.3162
Epoch 12/20
6580/6680 [============================>.] - ETA: 0s - loss: 9.5331 - acc: 0.3991Epoch 00012: val_loss improved from 10.14360 to 10.02629, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 266us/step - loss: 9.5392 - acc: 0.3985 - val_loss: 10.0263 - val_acc: 0.3222
Epoch 13/20
6540/6680 [============================>.] - ETA: 0s - loss: 9.4959 - acc: 0.4002Epoch 00013: val_loss improved from 10.02629 to 9.96576, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 267us/step - loss: 9.4901 - acc: 0.4006 - val_loss: 9.9658 - val_acc: 0.3246
Epoch 14/20
6600/6680 [============================>.] - ETA: 0s - loss: 9.3399 - acc: 0.4056Epoch 00014: val_loss improved from 9.96576 to 9.84095, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 265us/step - loss: 9.3420 - acc: 0.4055 - val_loss: 9.8409 - val_acc: 0.3341
Epoch 15/20
6620/6680 [============================>.] - ETA: 0s - loss: 9.2086 - acc: 0.4195Epoch 00015: val_loss improved from 9.84095 to 9.76075, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 261us/step - loss: 9.2204 - acc: 0.4186 - val_loss: 9.7607 - val_acc: 0.3353
Epoch 16/20
6620/6680 [============================>.] - ETA: 0s - loss: 9.1160 - acc: 0.4254Epoch 00016: val_loss improved from 9.76075 to 9.70056, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 260us/step - loss: 9.1142 - acc: 0.4253 - val_loss: 9.7006 - val_acc: 0.3389
Epoch 17/20
6620/6680 [============================>.] - ETA: 0s - loss: 9.0780 - acc: 0.4305Epoch 00017: val_loss improved from 9.70056 to 9.69063, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 262us/step - loss: 9.0809 - acc: 0.4304 - val_loss: 9.6906 - val_acc: 0.3401
Epoch 18/20
6620/6680 [============================>.] - ETA: 0s - loss: 9.0531 - acc: 0.4323Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 2s 259us/step - loss: 9.0526 - acc: 0.4323 - val_loss: 9.7332 - val_acc: 0.3269
Epoch 19/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.9531 - acc: 0.4323Epoch 00019: val_loss improved from 9.69063 to 9.57037, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 263us/step - loss: 8.9572 - acc: 0.4322 - val_loss: 9.5704 - val_acc: 0.3533
Epoch 20/20
6580/6680 [============================>.] - ETA: 0s - loss: 8.8172 - acc: 0.4372Epoch 00020: val_loss improved from 9.57037 to 9.35417, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 267us/step - loss: 8.7903 - acc: 0.4388 - val_loss: 9.3542 - val_acc: 0.3581
Out[40]:
<keras.callbacks.History at 0x7f9b5ad074a8>

Load the Model with the Best Validation Loss

In [41]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [42]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 34.4498%

Predict Dog Breed with the Model

In [43]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    dog_names = [item[20:-1] for item in sorted(glob("/data/dog_images/train/*/"))]
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras. These are already in the workspace, at /data/bottleneck_features. If you wish to download them on a different machine, they can be found at:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception.

The above architectures are downloaded and stored for you in the /data/bottleneck_features/ folder.

This means the following will be in the /data/bottleneck_features/ folder:

DogVGG19Data.npz DogResnet50Data.npz DogInceptionV3Data.npz DogXceptionData.npz

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('/data/bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [45]:
### TODO: Obtain bottleneck features from another pre-trained CNN.
bottleneck_Xception = np.load('/data/bottleneck_features/DogXceptionData.npz')

train_Xception = bottleneck_Xception['train']
valid_Xception = bottleneck_Xception['valid']
test_Xception = bottleneck_Xception['test']

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer: VGG19 has 19 convolution layers. Deep layers could become saturated then degrade. By add shortcut, it trains faster and performs better[1]. Depthwise separable convolutions seems to improve further. And it conbines the residual connections[2]. The test accuracy for VGG19, Resnet50, Inception, Xception for 20 epochs is 46.89%, 80.62%, 79%, 85% expectively.

[1] Deep Residual Learning for Image Recognition, Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Su, https://arxiv.org/abs/1512.03385v1 [cs.CV]

In [47]:
### TODO: Define your architecture.
Xception_model = Sequential()

Xception_model.add(GlobalAveragePooling2D(input_shape=train_Xception.shape[1:]))
Xception_model.add(Dense(133, activation='softmax'))

Xception_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_3 ( (None, 2048)              0         
_________________________________________________________________
dense_5 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [48]:
### TODO: Compile the model.
Xception_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [49]:
# create and configure augmented image generator
from keras.preprocessing.image import ImageDataGenerator

datagen_train = ImageDataGenerator(
    width_shift_range=0.1,     # randomly shift images horizontally (10% of total width)
    height_shift_range=0.1,    # randomly shift images vertically (10% of total height)
    horizontal_flip=True)      # randomly flip images horizontally

datagen_valid = ImageDataGenerator(
    width_shift_range=0.1,     # randomly shift images horizontally (10% of total width)
    height_shift_range=0.1,    # randomly shift images vertically (10% of total height)
    horizontal_flip=True)      # randomly flip images horizontally

# fit augment image generator on data
datagen_train.fit(train_Xception)
datagen_valid.fit(valid_Xception)
/opt/conda/lib/python3.6/site-packages/keras/preprocessing/image.py:683: UserWarning: Expected input to be images (as Numpy array) following the data format convention "channels_last" (channels on axis 3), i.e. expected either 1, 3 or 4 channels on axis 3. However, it was passed an array with shape (6680, 7, 7, 2048) (2048 channels).
  ' (' + str(x.shape[self.channel_axis]) + ' channels).')
/opt/conda/lib/python3.6/site-packages/keras/preprocessing/image.py:683: UserWarning: Expected input to be images (as Numpy array) following the data format convention "channels_last" (channels on axis 3), i.e. expected either 1, 3 or 4 channels on axis 3. However, it was passed an array with shape (835, 7, 7, 2048) (2048 channels).
  ' (' + str(x.shape[self.channel_axis]) + ' channels).')
In [50]:
### TODO: Train the model.
from keras.callbacks import ModelCheckpoint  

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG19.hdf5',
                              verbose=1, save_best_only=True)
Xception_model.fit(train_Xception, train_targets,
               validation_data=(valid_Xception, valid_targets),
               epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6600/6680 [============================>.] - ETA: 0s - loss: 1.0693 - acc: 0.7362Epoch 00001: val_loss improved from inf to 0.54364, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 6s 828us/step - loss: 1.0614 - acc: 0.7376 - val_loss: 0.5436 - val_acc: 0.8299
Epoch 2/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.3966 - acc: 0.8747Epoch 00002: val_loss improved from 0.54364 to 0.48503, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 3s 488us/step - loss: 0.3977 - acc: 0.8744 - val_loss: 0.4850 - val_acc: 0.8467
Epoch 3/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.3266 - acc: 0.8962Epoch 00003: val_loss did not improve
6680/6680 [==============================] - 3s 494us/step - loss: 0.3274 - acc: 0.8955 - val_loss: 0.4885 - val_acc: 0.8503
Epoch 4/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.2737 - acc: 0.9153Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 3s 479us/step - loss: 0.2759 - acc: 0.9147 - val_loss: 0.4979 - val_acc: 0.8551
Epoch 5/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.2405 - acc: 0.9230Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 3s 470us/step - loss: 0.2399 - acc: 0.9232 - val_loss: 0.5079 - val_acc: 0.8587
Epoch 6/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.2185 - acc: 0.9339Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 3s 469us/step - loss: 0.2182 - acc: 0.9341 - val_loss: 0.5361 - val_acc: 0.8599
Epoch 7/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.1937 - acc: 0.9385Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 3s 478us/step - loss: 0.1937 - acc: 0.9383 - val_loss: 0.5526 - val_acc: 0.8503
Epoch 8/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.1791 - acc: 0.9450Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 3s 477us/step - loss: 0.1795 - acc: 0.9451 - val_loss: 0.5696 - val_acc: 0.8599
Epoch 9/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.1592 - acc: 0.9530Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 3s 503us/step - loss: 0.1595 - acc: 0.9530 - val_loss: 0.5373 - val_acc: 0.8587
Epoch 10/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.1455 - acc: 0.9564Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 3s 457us/step - loss: 0.1492 - acc: 0.9555 - val_loss: 0.5366 - val_acc: 0.8563
Epoch 11/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.1347 - acc: 0.9600Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 3s 481us/step - loss: 0.1362 - acc: 0.9599 - val_loss: 0.5921 - val_acc: 0.8539
Epoch 12/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.1230 - acc: 0.9620Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 3s 457us/step - loss: 0.1242 - acc: 0.9618 - val_loss: 0.6197 - val_acc: 0.8527
Epoch 13/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.1155 - acc: 0.9661Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 3s 424us/step - loss: 0.1148 - acc: 0.9660 - val_loss: 0.6148 - val_acc: 0.8539
Epoch 14/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.1073 - acc: 0.9690Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 3s 446us/step - loss: 0.1074 - acc: 0.9689 - val_loss: 0.5799 - val_acc: 0.8635
Epoch 15/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.1015 - acc: 0.9731Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 3s 458us/step - loss: 0.1013 - acc: 0.9732 - val_loss: 0.6231 - val_acc: 0.8611
Epoch 16/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.0958 - acc: 0.9705Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 3s 483us/step - loss: 0.0959 - acc: 0.9705 - val_loss: 0.6269 - val_acc: 0.8575
Epoch 17/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.0878 - acc: 0.9747Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 3s 475us/step - loss: 0.0883 - acc: 0.9744 - val_loss: 0.6863 - val_acc: 0.8611
Epoch 18/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0786 - acc: 0.9765Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 3s 478us/step - loss: 0.0798 - acc: 0.9763 - val_loss: 0.6702 - val_acc: 0.8515
Epoch 19/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.0757 - acc: 0.9781Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 3s 479us/step - loss: 0.0751 - acc: 0.9783 - val_loss: 0.6523 - val_acc: 0.8599
Epoch 20/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.0730 - acc: 0.9793Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 3s 477us/step - loss: 0.0725 - acc: 0.9795 - val_loss: 0.7071 - val_acc: 0.8551
Out[50]:
<keras.callbacks.History at 0x7f9b46b56e48>

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [51]:
### TODO: Load the model weights with the best validation loss.
Xception_model.load_weights('saved_models/weights.best.VGG19.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [52]:
### TODO: Calculate classification accuracy on the test dataset.
Xception_predictions = [np.argmax(Xception_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Xception]

# report test accuracy
test_accuracy = 100*np.sum(np.array(Xception_predictions) == np.argmax(test_targets, axis=1)) / len(Xception_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 82.6555%

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [53]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

def Xception_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_Xception(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = str(np.argmax(Xception_model.predict(bottleneck_feature)) + 1)
    # return dog breed that is predicted by the model
    dog_names = [item[20:-1] for item in sorted(glob("/data/dog_images/train/*/"))]
    for i in range(0, len(dog_names)):
            if predicted_vector in dog_names[i]:
                return dog_names[i]    
    

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [64]:
Red = '\033[91m'
BLUE = "\033[1;34m"
End = '\033[0m'

def red_text(text):
    return '\033[1;31m {} \033[0m'.format(text)

def blue_text(text):
    return '\033[1;34m {} \033[0m'.format(text)
In [55]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

# dectect image is a dog or human
def classifier_dectector(img_path):
    classifier = red_text('Unknown')
    try:
        if(dog_detector(img_path)):
            classifier = 'dog'
        elif(face_detector(img_path)):
            classifier = 'human'
    except Exception as e:
        print(img_path)
        print(e)
        return classifier
    if "dog" in img_path and classifier == 'human':
        print(red_text("This time the prediction is wrong. You are a dog, but is mistaken for a human."))
    elif "lfw" in img_path and classifier == 'dog':
        print(red_text("This time the prediction is wrong. You are a human, but is mistaken for a dog."))
    return classifier
In [56]:
# show the image according the path
def img_shown(img_path):
    # load color (BGR) image
    img = cv2.imread(img_path, 1)

    # convert BGR image to RGB for plotting
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    
    # display the image, along with bounding box
    plt.imshow(cv_rgb)
    plt.show()
In [57]:
# show the dog image according the dog name
def dog_shown(predict_name):
    for i in range(0, len(train_files)):
        if predict_name in train_files[i]:
            img_shown(train_files[i])
            break
In [58]:
# get the name from the path whether it is a dog or a human
import re
def get_name_from_path(img_path):
    name = img_path.split('/')[-1]
    return re.split('[\d]', name)[0][:-1]
In [59]:
dog_names = glob("/data/dog_images/train/*/")
human_names = glob("/data/lfw/*/*")

# show the predict name and the according dog image even the input is a human
# if it is a dog, ouput the predict result, right or wrong and the real name
def img_prediction(img_path, classifier):
    real_name = get_name_from_path(img_path)
    print("You look like:")
    predict_name = Xception_predict_breed(img_path)
    predict_name = predict_name.split('.')[1]
    print(predict_name)
    if(classifier == "dog"):
        print("So I guess your name is {}.".format(predict_name))
        dog_shown(predict_name)
        if(predict_name == real_name):
            print(blue_text("Great. I guess right. You are really {}.".format(real_name)))
        else:
            print(red_text("It's sad. I guess wrong. You are {}.".format(real_name)))
    else:
        dog_shown(predict_name)
    print()
In [60]:
def img_detection(img_path):
    classifier = classifier_dectector(img_path)
    if classifier == red_text('Unknown'):
        print(red_text('It is vague to detect you are a dog or human.'))
        img_shown(img_path)
         print('You are from {}'.format(img_path))
        return;
    elif classifier is 'human':
        print('Hello, {}'.format(get_name_from_path(img_path)))
    else:
        print('Hello, dog')
    img_shown(img_path)
    img_prediction(img_path, classifier)
    print('You are from {}'.format(img_path))

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: This ouput is a little worse than expected. For human images, it's weird to find that this algorithm prefers to predict human to Dachshund and Petit_basset_griffon_vendeen. These two dogs appears frequently in human predictions during my test. What' more, I feel the color and number are important factors in prediction. For example, if the human is in gray clothes, it predicts gray dog. If the human is in black clothes, it predicts black dog. If there are two humans in a image, it predicts two dogs in a image. For dogs, It predicts all right this time. Usually it can predict right 9 out of 10.

For improvement, first, I want to clean the backgroud. It brings much disturbation. Maybe the same person in different places or wear differece clothes may have different predictions. In fact, he is still himself. A larger number of data is essential. It can solve the overfit.
Second, more iterations can help improve the accuracy. At the other hand it will takes much time. Considering the time, we set the epochs to 20. I think it is not enough to get a high accuracy. Third, we can tune with different parameters in detail, like the learning rate, optimizer and so on.

In [66]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.

human_files = np.array(glob("/data/lfw/*/*"))
random.shuffle(human_files)

dog_files, dog_targets = load_dataset('/data/dog_images/test')
random.shuffle(dog_files)

total_times = 20
for i in range(0, total_times//2):
    print("Round {}:".format(i))
    img_detection(human_files[i])
    print("=================================================================================")
for i in range(0, total_times//2):
    print("Round {}:".format(total_times/2 + i))
    img_detection(dog_files[i])
    print("=================================================================================")
Round 0:
Hello, Roberto_Carlos
You look like:
Dachshund
You are from /data/lfw/Roberto_Carlos/Roberto_Carlos_0001.jpg
=================================================================================
Round 1:
Hello, Kirk_Johnson
You look like:
Dogue_de_bordeaux
You are from /data/lfw/Kirk_Johnson/Kirk_Johnson_0002.jpg
=================================================================================
Round 2:
Hello, Justin_Guarini
You look like:
Irish_water_spaniel
You are from /data/lfw/Justin_Guarini/Justin_Guarini_0002.jpg
=================================================================================
Round 3:
Hello, Richard_Haass
You look like:
Petit_basset_griffon_vendeen
You are from /data/lfw/Richard_Haass/Richard_Haass_0002.jpg
=================================================================================
Round 4:
Hello, Ronaldo_Luis_Nazario_de_Lima
You look like:
Australian_cattle_dog
You are from /data/lfw/Ronaldo_Luis_Nazario_de_Lima/Ronaldo_Luis_Nazario_de_Lima_0001.jpg
=================================================================================
Round 5:
Hello, Harry_Belafonte
You look like:
English_toy_spaniel
You are from /data/lfw/Harry_Belafonte/Harry_Belafonte_0002.jpg
=================================================================================
Round 6:
Hello, Abdel_Madi_Shabneh
You look like:
Dachshund
You are from /data/lfw/Abdel_Madi_Shabneh/Abdel_Madi_Shabneh_0001.jpg
=================================================================================
Round 7:
Hello, Sylvester_Stallone
You look like:
Petit_basset_griffon_vendeen
You are from /data/lfw/Sylvester_Stallone/Sylvester_Stallone_0003.jpg
=================================================================================
Round 8:
Hello, Vicente_Fox
You look like:
Chinese_crested
You are from /data/lfw/Vicente_Fox/Vicente_Fox_0003.jpg
=================================================================================
Round 9:
Hello, Ted_Maher
You look like:
English_toy_spaniel
You are from /data/lfw/Ted_Maher/Ted_Maher_0001.jpg
=================================================================================
Round 10.0:
Hello, dog
You look like:
German_shepherd_dog
So I guess your name is German_shepherd_dog.
 Great. I guess right. You are really German_shepherd_dog. 

You are from /data/dog_images/test/071.German_shepherd_dog/German_shepherd_dog_04961.jpg
=================================================================================
Round 11.0:
Hello, dog
You look like:
Belgian_malinois
So I guess your name is Belgian_malinois.
 Great. I guess right. You are really Belgian_malinois. 

You are from /data/dog_images/test/020.Belgian_malinois/Belgian_malinois_01472.jpg
=================================================================================
Round 12.0:
Hello, dog
You look like:
Labrador_retriever
So I guess your name is Labrador_retriever.
 Great. I guess right. You are really Labrador_retriever. 

You are from /data/dog_images/test/096.Labrador_retriever/Labrador_retriever_06478.jpg
=================================================================================
Round 13.0:
Hello, dog
You look like:
Pomeranian
So I guess your name is Pomeranian.
 Great. I guess right. You are really Pomeranian. 

You are from /data/dog_images/test/123.Pomeranian/Pomeranian_07861.jpg
=================================================================================
Round 14.0:
Hello, dog
You look like:
Australian_terrier
So I guess your name is Australian_terrier.
 Great. I guess right. You are really Australian_terrier. 

You are from /data/dog_images/test/013.Australian_terrier/Australian_terrier_00897.jpg
=================================================================================
Round 15.0:
Hello, dog
You look like:
Keeshond
So I guess your name is Keeshond.
 Great. I guess right. You are really Keeshond. 

You are from /data/dog_images/test/092.Keeshond/Keeshond_06264.jpg
=================================================================================
Round 16.0:
Hello, dog
You look like:
Irish_terrier
So I guess your name is Irish_terrier.
 Great. I guess right. You are really Irish_terrier. 

You are from /data/dog_images/test/087.Irish_terrier/Irish_terrier_05887.jpg
=================================================================================
Round 17.0:
Hello, dog
You look like:
Border_terrier
So I guess your name is Border_terrier.
 Great. I guess right. You are really Border_terrier. 

You are from /data/dog_images/test/030.Border_terrier/Border_terrier_02110.jpg
=================================================================================
Round 18.0:
Hello, dog
You look like:
Australian_shepherd
So I guess your name is Australian_shepherd.
 Great. I guess right. You are really Australian_shepherd. 

You are from /data/dog_images/test/012.Australian_shepherd/Australian_shepherd_00853.jpg
=================================================================================
Round 19.0:
Hello, dog
You look like:
Borzoi
So I guess your name is Borzoi.
 Great. I guess right. You are really Borzoi. 

You are from /data/dog_images/test/031.Borzoi/Borzoi_02181.jpg
=================================================================================

Please download your notebook to submit

In order to submit, please do the following:

  1. Download an HTML version of the notebook to your computer using 'File: Download as...'
  2. Click on the orange Jupyter circle on the top left of the workspace.
  3. Navigate into the dog-project folder to ensure that you are using the provided dog_images, lfw, and bottleneck_features folders; this means that those folders will not appear in the dog-project folder. If they do appear because you downloaded them, delete them.
  4. While in the dog-project folder, upload the HTML version of this notebook you just downloaded. The upload button is on the top right.
  5. Navigate back to the home folder by clicking on the two dots next to the folder icon, and then open up a terminal under the 'new' tab on the top right
  6. Zip the dog-project folder with the following command in the terminal: zip -r dog-project.zip dog-project
  7. Download the zip file by clicking on the square next to it and selecting 'download'. This will be the zip file you turn in on the next node after this workspace!